package ru.ognick.coachsystem.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

public class IOFile {
    public static final String TAG = "JsonIO";
 
   	static private final File root = new File(Environment.getExternalStorageDirectory(), 
   											  "coach");
   	
   	static {
   		if (!root.exists()) 
   			 root.mkdir();
   	}


    
	private IOFile() {
//	it's static class
	}
    
    public static File[] getFiles() {
	    return root.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String filename) {
				return filename.endsWith(".js");
			}
		});
    }
    
    public static String loadTextFile(File file) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		byte buffer[] = new byte[(int)file.length()];
		bis.read(buffer,0,buffer.length);  
		fis.close();
		return new String(buffer);
	}
    
    public static File touchFile(String filename) {
		try {
			File file = new File (root, filename + ".js" );
			file.createNewFile();
			return file;
		} catch (IOException e) {
			Log.e(TAG,e.getMessage());
		}
		Log.e(TAG, "Can't create " + filename);
		return null;
    }
    
    public static boolean removeFile(File file){
    	return file.delete();
    }
    
    public static File renameFile(File oldfile, String filename) {
		File newfile = new File (root, filename + ".js" );
    	oldfile.renameTo(newfile);
    	return newfile;
    }
    
    public static void saveTextFile(File file, String text) throws IOException {
        try {
  			file.createNewFile();
  	        FileOutputStream fos = new FileOutputStream(file);
        	fos.write(text.getBytes());
        	fos.close();
        } catch (IOException e) {
        	Log.e(TAG,e.getMessage());
        }
	}
}
